package com.hh.config;

import cn.hutool.core.util.ObjUtil;
import com.hh.entity.domain.User;
import com.hh.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@Slf4j
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

@Override
public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, @NotNull Map<String, Object> attributes) {
    if (request instanceof ServletServerHttpRequest) {
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        // 获取请求参数
        User loginUser = userService.getLoginUser(servletRequest);
        if (ObjUtil.isEmpty(loginUser)) {
            log.error("用户未登录，拒绝握手");
            return false;
        }
        // 设置 attributes
        attributes.put("user", loginUser);
        attributes.put("userId", loginUser.getId());
        log.info("WebSocket握手成功，用户ID: {}", loginUser.getId());
        return true;
    }
    log.warn("WebSocket握手失败，请求类型不匹配");
    return false;
}


    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Exception exception) {
    }
}
